<?php

namespace Trawind\Skeleton\Generators;

use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Str;
use Trawind\Tenancy\Traits\TenantTool;

/**
 * Class TransformerGenerator
 * @package Prettus\Repository\Generators
 * @author Anderson Andrade <contato@andersonandra.de>
 */
class TransformerGenerator extends Generator
{
    use TenantTool;

    /**
     * Get stub name.
     *
     * @var string
     */
    protected $stub = 'transformer/transformer';

    /**
     * Get root namespace.
     *
     * @return string
     */
    public function getRootNamespace()
    {
        return parent::getRootNamespace().parent::getConfigGeneratorClassPath($this->getPathConfigNode());
    }

    /**
     * Get generator path config node.
     *
     * @return string
     */
    public function getPathConfigNode()
    {
        return 'transformers';
    }

    /**
     * Get destination path for generated file.
     *
     * @return string
     */
    public function getPath()
    {
        return $this->getBasePath().'/'.parent::getConfigGeneratorClassPath($this->getPathConfigNode(),
                true).'/'.$this->getName().'Transformer.php';
    }

    /**
     * Get base path of destination file.
     *
     * @return string
     */
    public function getBasePath()
    {
        return config('repository.generator.basePath', app()->path());
    }

    /**
     * Get array replacements.
     *
     * @return array
     */
    public function getReplacements()
    {
        $modelGenerator = new ModelGenerator([
            'name' => $this->name
        ]);
        $model = $modelGenerator->getRootNamespace().'\\'.$modelGenerator->getName();
        $model = str_replace([
            "\\",
            '/'
        ], '\\', $model);

        return array_merge(parent::getReplacements(), [
            'model' => $model,
            'table_field' => $this->getTableField(),
        ]);
    }


    public function getTableField()
    {
        return $this->runTenantOrCentral(function () {
            $tables = Schema::getColumnListing($this->getTableName());

            $columnStr = '';
            $timeMap=['created_at','updated_at'];

            foreach ($tables as $column) {
                $tabPlaceholder = empty($columnStr) ? '' : '            ';

                $columnLable='$model->'.$column;
                if(in_array($column,$timeMap)){
                    $columnLable='__date_time('.'$model->'.$column.')';
                    //                    $columnLable='is_null('.'$model->'.$column.')?'.$columnLable.':'.$columnLable."->format('Y-m-d H:i:s')";
                }
                $columnStr .= $tabPlaceholder."'$column' => ".$columnLable.','.PHP_EOL;
            }
            return $columnStr;
        });
    }


    public function getTableName()
    {
        $tableName = str_replace('/', '_', strtolower(preg_replace('/((?<=[a-z])(?=[A-Z]))/', '_', $this->getName())));
        return Str::plural($tableName);
    }
}
